<?php

namespace app\controller;


use app\BaseController;
use app\dto\PageDto;
use app\dto\TemplateArrayDto;
use app\dto\UserDto;
use app\model\GField;
use app\model\GTable;
use app\model\Menu;
use app\model\ModifyQuery;
use app\model\SysClass;
use app\model\SysDictionary;
use app\model\User;
use app\model\BaseQuery;
use app\model\WenZhang;
use app\Request;
use app\service\RedisService;
use app\utils\Axios;
use app\utils\FileUtills;
use app\utils\Md5;
use app\utils\Utils;
use app\validate\WenzhangValidate;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Env;
use think\facade\Log;


class GTableController extends BaseController
{


    function pageList(Request $request)
    {
        $params = $request->all();
        $query = BaseQuery::build(GTable::class);
        if (Utils::isNotNull($params, 'id')) {
            $query->where('id', $params['id']);
        }
        if (Utils::isNotNull($params, 'parentId')) {
            $query->where('parentId', $params['parentId']);
        }
        if (Utils::isNotNull($params, 'name')) {
            $query->where('name', 'like', "{$params['name']}%");
        }

        $query->page(Utils::getWithDefault($params, 'pageNum', 0))
            ->limit(Utils::getWithDefault($params, 'pageSize', 10));
        $resultlist = Utils::toHumpForArray($query->select());
        $total = $query->count();
        return json([
            "data" => $resultlist,
            "count" => $total
        ]);
    }

    function getItem(Request $request)
    {
        $id = $request->get("id");
        $parentId = $request->get("parentId");
        $query = BaseQuery::build(GTable::class);
        if (isset($id)) {
            $query->where('id', $id);
        }
        if (isset($parentId)) {
            $query->where('$parentId', $parentId);
        }
        $resultlist = $query->find();
        return Utils::ok($resultlist);
    }

    function add(Request $request)
    {
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("没有参数");
        }
        unset($params['id']);
        if (Utils::isNullPlus($params, 'tableName')) {
            return Utils::failRes("没有参数,tableName");
        }
        $id = GTable::create($params);

        return Utils::ok($id);
    }

    function update(Request $request)
    {
        $params = $request->all();
        /*校验 */
        if (Utils::isNullPlus($params, 'id')) {
            return Utils::failRes("id 必填");
        }
        /*查询是否存在*/
        $query = BaseQuery::build(GTable::class);
        $one = $query->where("id", $params['id'])->find();
        if (Utils::isNullPlus($one, 'id')) {
            return Utils::failRes("id:{$params['id']} 没有找到数据");
        }
        $resultint = GTable::update($params, [
            'id' => $params['id']
        ]);

        return Utils::ok($resultint);
    }

    function del(Request $request)
    {
        $id = $request->get("id");
        if (!isset($id)) {
            return Utils::failRes("id参数不能为空");
        }
        $userone = GTable::find($id);

        if (Utils::isNull($userone)) {
            return Utils::failRes("id: {$id} 找不到数据");
        }

        $result = BaseQuery::build(GTable::class)->where("id", $id)
            ->useSoftDelete('delete_time', Utils::dateyyyymmddhhmmss(time()))
            ->delete();
        return Utils::ok($result);
    }

    /**
     * @desc  解析参数dll 生成gtable+gfield
     * 1 解析ddl  新增 gtable
     * 2 新增 gfiled
     */
    function passddl(Request $request)
    {
        Log::info("> 开始进入 passddl");
        $ddl = $request->post("sql");
        $serverUrl = Env::get("NODEJSSERVICE.parseddl");
        Log::info("serverUrl===>$serverUrl");
        $result = Axios::post($serverUrl,
            ['ddl' => $ddl]
        );
//        $result=Axios::post("http://www.baidu.com",
//            ['ddl'=>$ddl]
//        );
        if (!isset($result['data'])) {
            return Utils::failRes("ddl解析失败");
        }
        $data = $result['data'];
        $tableSource = $data['title'];
        $definitions = $data['definitions'];
        $tableElementList = [];
        foreach ($definitions as $key => $item) {
            array_push($tableElementList, [
                'filedNameChinese' => $item['description'] ?? '',
                'comment' => $item['$comment'] ?? $item['description'] ?? '',
                'filedName' => $key,
                'name' => $key,
                'filedType' => $item['format'] ?? $item['type'] ?? '',
                'dateType' => $item['format'] ?? $item['type'] ?? '',


            ]);
        }

        return Utils::ok([
            "tableSource" => $tableSource,
            /*
             * filedNameChinese
             * comment
             * filedName
             * name
             * filedType
             * */
            "tableElementList" => $tableElementList
        ]);
    }

    /**
     * @desc  新增 gtable + gfield
     *
     */
    function addTableWithElementList(Request $request)
    {
        /*校验参数*/
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("没有参数");
        }
        if (Utils::isNullPlus($params, 'tableSource')) {
            return Utils::failRes("参数 tableSource ，必填");
        }
        if (Utils::isNullPlus($params, 'tableElementList')) {
            return Utils::failRes("参数 tableElementList ，必填");
        }
        $tableElementList = $params['tableElementList'];
        //region  新增 gtable  1 判断是否已经存在tablesource 新增，修改
        $gtableOne = GTable::where('table_name', $params['tableSource'])->find();

        $gtableId = '';
        if (Utils::isNotNull($gtableOne, 'id')/*存在 修改*/) {
            $gtableId = $gtableOne['id'];
            GTable::update([
                "tableName" => $params['tableSource']
            ], [
                'id' => $gtableId
            ]);
        } else { //新增  $gtableId=$gtableOne['id']
            $addResult = GTable::create([
                "tableName" => $params['tableSource']
            ]);
            Log::info("> 新增之后的数据是 $addResult");
            $gtableId = $addResult['id'];

        }

        //endregion

        //region  开始修改 gfield
        foreach ($tableElementList as &$item) {
            $item['gTableId'] = $gtableId;

        }
        $GFEILD = new GField();
        $GFEILD->saveAll($tableElementList);

        //endregion

        return Utils::ok(null);
    }

    /**
     * @desc  根据 模板json 生成zip
     *
     */
    function zipCodeByTemplate(Request $request)
    {
        $json = $request->all();
        $params = Utils::copyProperties(TemplateArrayDto ::class, $json);
        if (!isset($params)) {
            return Utils::failRes("参数  是空");
        }
        if (empty($params->fileList)) {
            return Utils::failRes("fileList  是空");
        }
        $result = FileUtills::zipFileArray($params->fileList);
        return $result;
    }


}